<script setup>
import { ref, onMounted, defineProps, defineEmits } from 'vue'
const props = defineProps({
    modelValue: {
        required: true,
    },
    data: {
        type: Array,
        default: () => []
    },
    model: {
        type: Number,
        default: () => 0
    }
})
let emits = defineEmits(['update:modelValue'])

let radioButtonBody = ref(null);
let box = ref(null);
let offset=0;
function computedOffset(parentDom){
    let domArr=Array.from(parentDom.children??[]);
    let min=Number.MAX_VALUE;
    let model=props.model??0;
    domArr.forEach(item => {
        if(item===box.value){
            return;
        }
        if(model!=0&& item.offsetLeft<min){
            min=item.offsetLeft;
        }else if(model==0 && item.offsetTop<min){
            min=item.offsetTop;
        }
    });
    return min<1?1:min;
}
function setPosition(dom){
    if (props.model === 0) {
        box.value.style.left = (dom.offsetLeft-offset) + 'px';
        box.value.style.width = (dom.clientWidth+2*offset) + 'px';
    } else {
        box.value.style.top = (dom.offsetTop-offset) + 'px';
        box.value.style.height = (dom.clientHeight+2*offset) + 'px';
    }
}
function select(e, value) {
    emits('update:modelValue', value);
    //移动滑块
    setPosition(e.target);
}
onMounted(() => {
    offset=computedOffset(radioButtonBody.value);
    initBox();
})
function initBox() {
    //找到初始值
    let vArr = props.data ?? [];
    let modelValue = props.modelValue ?? 0;
    let indexValue = 0;
    vArr.some((item, index) => {
        if (item.value == modelValue) {
            indexValue = index;
            return true;
        }
    })
    let dom = radioButtonBody.value.children[indexValue];
    setPosition(dom)
}
</script>

<template>
    <section ref="radioButtonBody" :class="`radioButtonBody flex ${props.model == 1 ? 'column' : ''}`">
        <template v-for="(item, index) in props.data">
            <span class="item"
                :class="`${props.modelValue == item.value ? 'seleted' : ''} ${props.model == 0 ? 'itemMarginLeft' : 'itemMarginTop'}`"
                @click.stop="select($event, item.value)">{{ item.lable }}</span>
        </template>
        <span class="bgBox" ref="box"></span>
    </section>
</template>

<style scoped>
.seleted {
    color: white !important;
}

.bgBox {
    position: absolute;
    z-index: 0;
    height: 90%;
    width: 90%;
    border-radius: .5em;
    background: var(--color-theme);
    transition: all .3s;
}

.item {
    letter-spacing: .2em;
    position: relative;
    cursor: pointer;
    color: var(--color-text-third);
    z-index: 1;
}

.itemMarginTop {
    margin: .5em;
}

.itemMarginLeft {
    margin: .5em;
}

.radioButtonBody {
    background-color: var(--color-text-fifth);
    border-radius: .5em;
    position: relative;
    display: flex;
    justify-content: space-evenly;
    align-items: center;
    overflow: hidden;
}

.column {
    flex-direction: column;
}</style>